package com.dd.stack.es.pojo.req;

import com.dd.stack.common.util.param.PageParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;

/**
 * @Author liuxianmeng
 * @CreateTime 2024/10/31 16:02
 * @Description product索引请求类
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel("product索引请求类")
public class ProductESReq {
    @ApiModelProperty("产品名")
    private String name;
    @ApiModelProperty("产品价格")
    private Double price;
    @ApiModelProperty("产品描述")
    private String description;
    @ApiModelProperty("分页参数")
    private PageParams pageReq;

    /**
     * 构建分页信息
     *
     * @return Pageable
     */
    public Pageable buildPageable() {
        return PageRequest.of(this.getPageReq().getPageNum() - 1, this.getPageReq().getPageSize());
    }

    /**
     * 构建布尔查询
     *
     * @return BoolQueryBuilder
     */
    public BoolQueryBuilder buildBoolQuery() {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 添加查询条件
        if (StringUtils.hasText(this.getName())) {
            boolQuery.must(QueryBuilders.wildcardQuery("name", "*" + this.getName() + "*"));
        }
        if (this.getPrice() != null && this.getPrice() != 0) {
            boolQuery.must(QueryBuilders.termQuery("price", this.getPrice()));
        }
        if (StringUtils.hasText(this.getDescription())) {
            boolQuery.must(QueryBuilders.matchQuery("description", this.getDescription()));
        }

        return boolQuery;
    }
}
